package com.tt.easycache;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpConnector {

    private final static int DEFAULT_TIMEOUT = 15 * 1000;

    /**
     * 网络错误
     */
    public final static int NET_STATE_ERROR = -999;

    public static class Response {
        public int code;
        public String content;

        public Response(int code, String content) {
            this.code = code;
            this.content = content;
        }
    }

    /**
     * http请求String <功能简述>
     * 
     * @param url
     * @return
     */
    public static Response getHttpString(String url) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                DEFAULT_TIMEOUT);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
        HttpGet httpget = new HttpGet(url);
        try {
            HttpResponse response = httpclient.execute(httpget);
            int statuscode = response.getStatusLine().getStatusCode();
            return new Response(statuscode, EntityUtils.toString(response
                    .getEntity()));
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        } finally {
            httpget.abort();
            httpclient.getConnectionManager().shutdown();
        }
        return new Response(NET_STATE_ERROR, null);
    }
}
